/**
 *    this.props.api
 *    this.props.api_comments
 *    this.props.noSerch
 *    this.props.headName   // 标题名字
 *    this.props.Btns     // 可操作按钮
 */

import React from 'react';
import { Table, thead, tr, th, Button } from 'react-bootstrap';
import weAjax from '../utils/ajax'
import { dttoj } from '../utils/date'
import './data-table.css'
import FileSaver from 'file-saver'


// import TableUpdate from './data_update.js'

class DataTable extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            comments: [],
            dataList: [],// 原始数据，一般情况不操作
            filterDataList: [], // 负责显示serch或者列表
            error: null
        }
        this.onClick = this.onClick.bind(this);
        this.onDeleteBtn = this.onDeleteBtn.bind(this);
        this.selectItems = []; // 选中的那些元素
    }

    componentDidMount() {

        // 表注释和表数据请求
        if (this.props.api) {
            this.ajaxid = weAjax({ url: this.props.api_comments, method: 'get' }, (data) => {
                this.setState({
                    comments: data.data
                })

            });
            this.ajaxid2 = weAjax({ url: this.props.api, method: 'get' }, (data) => {
                this.setState({
                    dataList: data.data,
                    filterDataList: data.data
                })
                if (data.length <= 0) {
                    this.setState({
                        error: <div>暂无数据</div>
                    })
                }
            });
        }

    }

    componentWillUnmount() {
        if (this.ajaxid && this.ajaxid2) {
            this.ajaxid.abort();
            this.ajaxid2.abort();
        }

        if (this.ajaxid3) {
            for (let i = 0; i < this.ajaxid3.length; i++) {
                this.ajaxid3[i].abort();
            }

        }
    }

    onClick(e, b) {
        if (e.target.localName === 'tbody') return;
        const tr = e.target.parentElement;
        if (tr.className === 'active') {
            tr.className = '';
            for (let i = 0; i < this.selectItems.length; i++) {
                if (this.selectItems[i] === tr.rowIndex) {
                    this.selectItems.splice(i, 1);
                    return;
                }
            }
        } else {
            tr.className = 'active';
            this.selectItems.push(tr.rowIndex);
        }

    }

    /**
     * 下载此表格
     * (ps: 搜索到相应活动信息后，根据活动信息里的table_name字段来下载相应的数据
     *     不能直接使用table_name，这样做是越权)
     */
    onDownBtn = () => {
        this.ajaxid4 = weAjax({ url: this.props.api_down, method: 'get' }, (data) => {
            var blob = new Blob([data], { type: "text/plain;charset=utf-8" });
            FileSaver.saveAs(blob, "data.xls");
        });
    }

    /**
     * 删除所选内容
     */
    onDeleteBtn = () => {
        console.log(this.selectItems)

        // 拿取到key
        var deleteData = [];
        for (let i = 0; i < this.selectItems.length; i++) {
            deleteData.push(this.state.filterDataList[this.selectItems[i] - 1]);
        }

        // 时间字段筛选
        var willChangeIndexs = [];
        for (let i = 0; i < this.state.comments.length; i++) {
            if (this.state.comments[i].Type === "timestamp" || this.state.comments[i].Type === "datetime") {
                willChangeIndexs.push(this.state.comments[i].Field);
            }
        }
        // 修改时间字段的值
        for (let j = 0; j < deleteData.length; j++) {
            for (let i = 0; i < willChangeIndexs.length; i++) {
                deleteData[j][willChangeIndexs[i]] = dttoj(deleteData[j][willChangeIndexs[i]]).toLocaleString();
            }
        }
        // 清空null字段
        for (let j = 0; j < deleteData.length; j++) {
            for (let i in deleteData[j]) {
                if (deleteData[j][i]) {
                    continue;
                } else {
                    delete deleteData[j][i];
                }
            }
        }

        // 删除
        var url = this.props.api + '&';
        this.ajaxid3 = [];

        // 循环删除所选择内容
        var count = 0;
        var fd = this.state.filterDataList;
        for (let i = 0; i < deleteData.length; i++) {
            this.ajaxid3.push(
                weAjax({ url: url + '&id=' + deleteData[i].id, method: 'delete' }, (data) => {

                    count++;
                    if (count >= deleteData.length) {

                        for (let i = 0; i < deleteData.length; i++) {
                            for (let j = 0; j < fd.length; j++) {
                                if (deleteData[i].id === fd[j].id) {
                                    fd.splice(j - 1, 1);
                                }
                            }

                        }
                        this.setState({ filterDataList: fd, dataList: fd })
                        alert("删除成功")
                    }
                })
            )
        }
        this.selectItems = [];
    }

    onSerchChange = (e) => {
        if (!e.target.value) {
            this.setState({ filterDataList: this.state.dataList })
            return;
        }

        var dataList = this.state.dataList;
        var filterDataList = [];

        for (let i = 0; i < dataList.length; i++) {
            for (let j in dataList[i]) {
                if (dataList[i][j] && dataList[i][j].toString().indexOf(e.target.value) >= 0) {
                    filterDataList.push(dataList[i]);
                    break;
                }
            }
        }
        this.setState({ filterDataList: filterDataList })
    }

    render() {
        // let error = null;
        let serch = null;
        let table = null;
        let btns = null;
        // let btns = null;

        if (this.state.dataList.length > 0) {
            if (this.props.noSerch) {
                serch = null;
            } else {
                serch = <input className="activity-serch-input" type="text" placeholder="serch..." onChange={this.onSerchChange}></input>;
            }
            table = (
                <Table striped hover condensed bordered className="my-table">
                    <thead>
                        <tr>
                            {this.state.comments.map((item, i) => ( // 遍历注释
                                <th key={i}>{item.Comment}</th>
                            ))}
                        </tr>
                    </thead>
                    <tbody onClick={this.onClick}>
                        {this.state.filterDataList.map((item, i) => (  // 遍历数据
                            <tr key={i} >
                                {this.state.comments.map((commentItem, j) => ( // 根据遍历数据中的数据，再遍历子项目
                                    <td key={j}>{
                                        (commentItem.Type === "timestamp" || commentItem.Type === "datetime") // 如果为时间类字段，做转义
                                            ? dttoj(item[commentItem.Field]).toLocaleString() : item[commentItem.Field]
                                    }
                                    </td>))
                                }
                            </tr>
                        ))}
                    </tbody>
                </Table>
            )

            if (this.props.btns) {
                btns = (
                    <div className="data-table-Btns">
                        {this.props.btns.indexOf('downBtn') > -1 ? <Button bsStyle="info" onClick={this.onDownBtn}>下　　载</Button> : ''}
                        {this.props.btns.indexOf('deleteBtn') > -1 ? <Button bsStyle="info" onClick={this.onDeleteBtn}>删除选中</Button> : ''}
                    </div>
                )
            }

        }

        return (
            <div className="fadeIn">
                <h2 className='left-nv-title'>{this.props.headName || this.props.name}</h2>
                {this.state.error}
                {serch}
                {btns}
                {table}
            </div>
        )
    }
}

export default DataTable;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  